<template>
  <div class="workbench">
    <!-- 筛选条件 -->
    <ContentWrap>
      <el-form
        ref="queryFormRef"
        class="-mb-15px"
        :model="queryParams"
        :inline="false"
        label-width="130px"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="时间范围" prop="dateRange">
              <!-- <el-date-picker
                v-model="queryParams.dateRange"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                class="!w-240px"
              /> -->
                <div class="time-box">
                <el-date-picker
                  style="width: 220px"
                  v-model="queryParams.stime"
                  size="mini"
                  type="date"
                  :editable="false"
                  :clearable="true"
                  placeholder="开始日期"
                  :disabled-date="disableStartDate"
                />
                <span class="time-line">-</span>
                <el-date-picker
                  style="width: 220px"
                  v-model="queryParams.etime"
                  size="mini"
                  :editable="false"
                  :clearable="true"
                  type="date"
                  placeholder="结束日期"
                  :disabled-date="disableEndDate"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="16" class="text-right">
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <!-- <el-button type="primary" @click="resetQuery">导出报告</el-button> -->
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </ContentWrap>
    <ContentWrap>
      <div id="container" class="container"></div>
    </ContentWrap>
  </div>
</template>

<script lang="ts" setup name="workbench">
import * as dataAnalysisApi from '@/api/patient/dataAnalysis'
import Highcharts from 'highcharts'
import Heatmap from 'highcharts/modules/heatmap.js'
import Exporting from 'highcharts/modules/exporting'
import ExportData from 'highcharts/modules/export-data'

// 初始化模块（关键）
if (typeof Heatmap === 'function') {
  Heatmap(Highcharts)
}
if (typeof Exporting === 'function') {
  Exporting(Highcharts)
}
if (typeof ExportData === 'function') {
  ExportData(Highcharts)
}
const queryParams = reactive({
  stime: '',
  etime: '',
  dateRange: [],
  times: [] as string[]
})


// 禁止选择晚于结束日期的开始时间
function disableStartDate(date: Date) {
  const today = new Date();

  if (queryParams.etime) {
    if (date.getTime() > new Date(queryParams.etime).getTime()) {
      return true; // 晚于结束时间
    }
  }

  if (date.getTime() > today.getTime()) {
    return true; // 晚于今天
  }

  return false;
}

// 禁止选择早于开始日期的结束时间
function disableEndDate(date: Date) {
   const today = new Date();

  if (queryParams.stime) {
    const stime = new Date(queryParams.stime);

    if (date.getTime() < stime.getTime()) {
      return true; // 早于开始时间
    }

    const maxEnd = new Date(stime);
    maxEnd.setFullYear(maxEnd.getFullYear() + 1); // 开始时间 + 1 年

    if (date.getTime() > maxEnd.getTime()) {
      return true; // 跨度超 1 年
    }
  }

  if (date.getTime() > today.getTime()) {
    return true; // 晚于今天
  }

  return false;
}
//监听stime和etime，发生变化修改times的值
watch(
  () => [queryParams.stime, queryParams.etime],
  ([newStime, newEtime]) => {
    queryParams.dateRange = newStime && newEtime ? [newStime, newEtime] : []
  }
)
const handleQuery = () => {
  if (queryParams.dateRange && queryParams.dateRange.length === 2) {
    queryParams.times = queryParams.dateRange
  } else {
    queryParams.times = []
  }
  initTable()
}
const resetQuery = () => {
  queryParams.stime = ''
  queryParams.etime = ''
  queryParams.dateRange = []
  queryParams.times = []
  initTable()
}
const initTable = async () => {
  // Substring template helper for the responsive labels
  Highcharts.Templating.helpers.substr = (s, from, length) => s.substr(from, length)
  const data = await dataAnalysisApi.getDataAnalysis(queryParams)
  const xLable = []
  const boxData = []
  data?.forEach((element, index) => {
    xLable.push(element.deptName)
    boxData.push([index, 0, element.patientIncreaseCount])
    boxData.push([index, 1, element.patientCureCount])
    boxData.push([index, 2, element.stoppingTreatmentCount])
  })
  // Create the chart
  Highcharts.chart('container', {
    chart: {
      type: 'heatmap',
      marginTop: 40,
      marginBottom: 80,
      plotBorderWidth: 1
    },

    title: {
      text: '各区县数据对比图',
      style: {
        fontSize: '1em'
      }
    },
    exporting: {
      enabled: true,
      fallbackToExportServer: false // 不请求远程服务，防止 CORS
    },
    xAxis: {
      categories: xLable,
      labels: {
        style: {
          fontSize: '16px' // 字体变大
        }
      }
    },

    yAxis: {
      categories: ['精神病人新增数', '治疗精神病人新增人数', '停止用药新增人数'],
      title: null,
      reversed: true,
      labels: {
        style: {
          fontSize: '16px' // 字体变大
        }
      }
    },
    colorAxis: {
      min: 0,
      minColor: '#FFFFFF',
      maxColor: Highcharts.getOptions().colors[0]
    },

    legend: {
      align: 'right',
      layout: 'vertical',
      margin: 0,
      verticalAlign: 'top',
      y: 25,
      symbolHeight: 280
    },

    tooltip: {
      format:
        '<b>{series.xAxis.categories.(point.x)}</b><br>' +
        '<b>{series.yAxis.categories.(point.y)}</b>  <b>{point.value}</b> 人'
    },

    series: [
      {
        name: '类别',
        borderWidth: 1,
        data: boxData,
        dataLabels: {
          enabled: true,
          color: '#000000',
          style: {
            fontSize: '18px' // 字体变大
          }
        }
      }
    ],
    exporting: {
      enabled: true,
      url: 'http://localhost:7801',
      buttons: {
        contextButton: {
          menuItems: [
            {
              text: '全屏查看',
              onclick: function () {
                this.fullscreen.toggle()
              }
            },
            {
              text: '打印图表',
              onclick: function () {
                this.print()
              }
            }
            // {
            //   separator: true
            // },
            // {
            //   text: '下载 PNG 图片',
            //   onclick: function () {
            //     this.exportChart({ type: 'image/png' })
            //   }
            // },
            // {
            //   text: '下载 JPEG 图片',
            //   onclick: function () {
            //     this.exportChart({ type: 'image/jpeg' })
            //   }
            // },
            // {
            //   text: '下载 SVG 矢量图',
            //   onclick: function () {
            //     this.exportChart({ type: 'image/svg+xml' })
            //   }
            // },
            //   {
            //   separator: true
            // },
            // {
            //   text: '下载 CSV 数据',
            //   onclick: function () {
            //     this.downloadCSV()
            //   }
            // },
            // {
            //   text: '下载 Excel (XLS)',
            //   onclick: function () {
            //     this.downloadXLS()
            //   }
            // }
          ]
        }
      }
    },
    credits: {
      enabled: false
    },
    responsive: {
      rules: [
        {
          condition: {
            maxWidth: 500
          },
          chartOptions: {
            yAxis: {
              labels: {
                format: '{substr value 0 1}'
              }
            }
          }
        }
      ]
    }
  })
}

onMounted(() => {
  initTable()
})
</script>

<style lang="scss" scoped>
.text-right {
  display: flex;
  justify-content: flex-end;
}
.container {
  width: 100%;
  // height: 550px;
  height: 660px;
}
.time-box {
  display: flex;
  gap: 5px;
}
</style>
